import java.util.ArrayList;
import java.util.List;

/**
 * @author ZCR
 * @create 2025/8/3 08:29
 */
public class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        for(int i=0;i < Math.min(matrix.length,matrix[0].length)-1;i++){
            for(int j =i;j <= matrix[0].length-i-2;j++){
                res.add(matrix[i][j]);
            }
            for(int j =i;j <= matrix.length-i-2;j++) {
                res.add(matrix[j][matrix[0].length - i-1]);
            }
            for(int j =matrix[0].length-i-1;j>i;j--){
                res.add(matrix[matrix.length-i-1][j]);
            }
            for(int j =matrix.length-i-1;j > i;j--) {
                res.add(matrix[j][i]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution54 solution54 = new Solution54();
//        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> list = solution54.spiralOrder(matrix);
        System.out.println(list);
    }
}
